package com.heima.leetcode.datastructure.binarytree;

import java.util.LinkedList;
import java.util.List;

/**
 * <strong>非递归实现中序遍历(都按照后序遍历的方式写) 94</strong>
 * @author 勾新杰
 * @version 1.0
 * @date 2024/9/8 11:05
 */
public class InOrderTraversal {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode curr = root;
        TreeNode lastPop = null;
        while (curr != null || !stack.isEmpty()){
            if (curr != null){
                stack.push(curr);
                curr = curr.left;
            }else {
                TreeNode last = stack.peek();
                if (last.right == null){
                    result.add(last.val);
                    lastPop = stack.pop();
                }else if (last.right == lastPop){
                    lastPop = stack.pop();
                }else {
                    result.add(last.val);
                    curr = last.right;
                }
            }
        }
        return result;
    }
}
